<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>个人中心</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
    <!-- 引入 FontAwesome 用于更多图标 -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

    <style>
        /* 状态标签样式 */
        .badge {
            font-weight: 500;
            padding: 0.4em 0.6em;
            font-size: 0.85em;
        }
        
        .bg-secondary { background-color: #6c757d !important; }
        .bg-success { background-color: #28a745 !important; }
        .bg-info { background-color: #17a2b8 !important; }
        .bg-danger { background-color: #dc3545 !important; }
        
        /* 列表项悬停效果 */
        .list-group-item:hover {
            background-color: #f1f1f1;
            transition: all 0.2s ease;
        }
        
        /* 按钮图标间距 */
        .btn i {
            margin-right: 0.3em;
        }
        
        /* 文章内容预览样式 */
        .article-content {
            line-height: 1.6;
            font-size: 1rem;
            white-space: pre-wrap;
            word-wrap: break-word;
        }
        
        /* 时间戳样式 */
        .text-muted {
            font-size: 0.85em;
        }
        
        /* 响应式调整 */
        @media (max-width: 768px) {
            .section-title {
                font-size: 1.25rem;
            }
            
            .list-group-item {
                flex-direction: column;
                align-items: flex-start;
            }
            
            .list-group-item .d-flex {
                width: 100%;
                justify-content: space-between;
            }
        }
    </style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light mb-4">
  <div class="container">
    <a class="navbar-brand fw-bold" th:href="@{/}">博客首页</a>
    <div class="d-flex">
<!--        <a class="btn btn-primary me-2" th:href="@{/user/new-article}" th:if="${#authentication?.authenticated}" title="发布新文章"><i class="bi bi-pencil-square"></i> 发布文章</a>-->
        <!-- 添加了认证判断的发布文章按钮 -->
      <a class="btn btn-primary me-2" th:href="@{/api/articles/newArticle}" title="发布新文章">
          <i class="bi bi-pencil-square"></i> 发布文章
      </a>
      <a class="btn btn-outline-primary me-2" th:href="@{/admin/dashboard}" th:if="${#authentication?.authenticated}">后台管理</a>
      <a class="btn btn-success" th:href="@{/logout}">退出登录</a>
    </div>
  </div>
</nav>
<div class="container">
    <div class="center-card">
        <!-- 用户信息头部，包含头像、用户名和注册时间 -->
        <div class="profile-header d-flex align-items-center p-3 mb-4 bg-white rounded shadow-sm">
            <!-- 显示用户头像，若无头像则使用默认头像 -->
            <img th:src="${user != null and user.avatar != null ? user.avatar : '/image/avatar0.jpg'}" alt="用户头像" class="avatar shadow-sm" style="width: 150px; height: 150px; border-radius: 50%;">

            <!-- 用户基础信息区域 -->
            <div class="profile-info ms-4">
                <!-- 显示当前登录用户名 -->
                <h3 class="mb-1 text-primary fw-bold" th:text="${user != null ? user.username : '未知'}">用户名</h3>
                <!-- 显示用户注册时间，若用户信息为空则显示“未知” -->
                <p class="text-muted mb-0">
                    <i class="bi bi-calendar3 me-1"></i>
                    <span th:text="${user != null ? user.createTime : '未知'}"></span>
                </p>
            </div>

            <!-- 操作按钮组 -->
            <div class="d-flex align-items-center ms-auto gap-2">
                <!-- 修改密码按钮 -->
                <button type="button" class="btn btn-outline-secondary btn-sm px-3 py-2 d-flex align-items-center gap-1"
                        data-bs-toggle="modal" data-bs-target="#passwordModal">
                    <i class="bi bi-key"></i> 修改密码
                </button>



                <!-- 上传头像表单 -->
                <form class="upload-avatar-form" id="avatarForm">
                    <input type="file" id="avatarInput" accept="image/*" style="display: none" onchange="uploadAvatar()">
                    <button type="button" class="btn btn-primary btn-sm px-3 py-2 d-flex align-items-center gap-1"
                            onclick="document.getElementById('avatarInput').click()">
                        <i class="bi bi-upload"></i> 上传头像
                    </button>
                </form>
            </div>
        </div>

        <div class="section-title mt-4 mb-3 d-flex align-items-center">
            <i class="bi bi-bar-chart-line-fill text-primary me-2"></i>
            <span>个人统计</span>
        </div>

        <div class="row g-3 mb-4">
            <div class="col-md-4">
                <div class="stat-card p-3 rounded-3 shadow-sm h-100">
                    <div class="d-flex align-items-center">
                        <div class="p-2 me-3 bg-primary bg-opacity-10 rounded-circle">
                            <i class="bi bi-journal-text text-primary fs-4"></i>
                        </div>
                        <div>
                            <h5 class="mb-1 text-muted">文章总数</h5>
                            <h3 class="mb-0 fw-bold" th:text="${userStats?.articleCount ?: 0}"></h3>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stat-card p-3 rounded-3 shadow-sm h-100">
                    <div class="d-flex align-items-center">
                        <div class="p-2 me-3 bg-success bg-opacity-10 rounded-circle">
                            <i class="bi bi-chat-left-text text-success fs-4"></i>
                        </div>
                        <div>
                            <h5 class="mb-1 text-muted">评论总数</h5>
                            <h3 class="mb-0 fw-bold" th:text="${userStats?.commentCount ?: 0}"></h3>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stat-card p-3 rounded-3 shadow-sm h-100">
                    <div class="d-flex align-items-center">
                        <div class="p-2 me-3 bg-warning bg-opacity-10 rounded-circle">
                            <i class="bi bi-eye-fill text-warning fs-4"></i>
                        </div>
                        <div>
                            <h5 class="mb-1 text-muted">累计点击量</h5>
                            <h3 class="mb-0 fw-bold" th:text="${userStats?.clickCount ?: 0}"></h3>
                        </div>
                    </div>
                </div>
            </div>
        </div>


    </div>

        <div class="row">
            <!-- 草稿箱 -->
            <div class="col-md-6">
                <div class="section-title d-flex align-items-center mb-3">
                    <i class="bi bi-folder me-2 text-warning"></i>
                    <span>草稿箱</span>
                </div>
                <ul class="list-group mb-4" th:if="${not #lists.isEmpty(draftArticles)}">
                    <li class="list-group-item d-flex justify-content-between align-items-center" th:each="article : ${draftArticles}">
                        <a th:href="@{'/api/articles/newArticle?draftId=' + ${article.articleId}}" 
                           class="text-decoration-none text-dark fw-medium">
                           <i class="bi bi-file-earmark-text me-2"></i>
                           <span th:text="${article.title}"></span>
                        </a>
                        <div>
                            <span class="badge bg-secondary me-2">草稿</span>
                            <button class="btn btn-link btn-sm text-danger p-0" 
                                    type="button"
                                    onclick="confirmDelete('article', /*[(${article.articleId})]*/)">
                                <i class="bi bi-trash3"></i>
                            </button>
                        </div>
                    </li>
                </ul>
                <div th:unless="${not #lists.isEmpty(draftArticles)}" class="text-muted">
                    <i class="bi bi-folder-check me-2"></i>暂无草稿
                </div>
            </div>
            
            <!-- 待审核文章 -->
            <div class="col-md-6">
                <div class="section-title d-flex align-items-center mb-3">
                    <i class="bi bi-hourglass me-2 text-info"></i>
                    <span>待审核文章</span>
                </div>
                <ul class="list-group mb-4" th:if="${not #lists.isEmpty(pendingArticles)}">
                    <li class="list-group-item d-flex justify-content-between align-items-center" th:each="article : ${pendingArticles}">
                        <span class="fw-medium">
                            <i class="bi bi-file-earmark-check me-2"></i>
                            <span th:text="${article.title}"></span>
                        </span>
                        <div>
                            <span class="badge bg-warning me-3">审核中</span>
                            <button class="btn btn-outline-primary btn-sm me-2" 
                                    type="button"
                                    onclick="viewArticle(/*[(${article.articleId})]*/)">
                                <i class="bi bi-eye"></i> 查看
                            </button>
                            <button class="btn btn-outline-danger btn-sm"
                                    type="button"
                                    onclick="retractArticle(/*[(${article.articleId})]*/)">
                                <i class="bi bi-arrow-clockwise"></i> 撤回
                            </button>
                        </div>
                    </li>
                </ul>
                <div th:unless="${not #lists.isEmpty(pendingArticles)}" class="text-muted">
                    <i class="bi bi-hourglass-split me-2"></i>暂无待审文章
                </div>
            </div>
        </div>

        <!-- 我的文章 -->
        <div class="col-md-6">
            <div class="section-title d-flex align-items-center mb-3">
                <i class="bi bi-journal me-2 text-primary"></i>
                <span>我的文章</span>
            </div>
            <ul class="list-group mb-4">
                <li class="list-group-item d-flex justify-content-between align-items-center" th:each="article : ${myArticles}">
                    <a th:href="@{'/article/' + ${article.articleId}}" 
                       class="text-decoration-none text-dark fw-medium">
                       <i class="bi bi-file-earmark-text me-2"></i>
                       <span th:text="${article.title}"></span>
                    </a>
                    <div>
                        <span th:switch="${article.status}">
                            <span th:case="0" class="badge bg-secondary me-2">草稿</span>
                            <span th:case="1" class="badge bg-success me-2">已发布</span>
                            <span th:case="2" class="badge bg-info me-2">待审核</span>
                            <span th:case="3" class="badge bg-danger me-2">被驳回</span>
                        </span>
                        <button class="btn btn-outline-primary btn-sm me-2" 
                                type="button"
                                onclick="editArticle(/*[(${article.articleId})]*/)">
                            <i class="bi bi-pencil"></i> 编辑
                        </button>
                        <button class="btn btn-outline-danger btn-sm"
                                type="button"
                                onclick="confirmDelete('article', /*[(${article.articleId})]*/)">
                            <i class="bi bi-trash3"></i> 删除
                        </button>
                    </div>
                </li>
                <li th:if="${#lists.isEmpty(myArticles)}" class="list-group-item text-muted">
                    <i class="bi bi-journal-x me-2"></i>暂无文章
                </li>
            </ul>
        </div>
        
        <!-- 我的评论 -->
        <div class="col-md-6">
            <div class="section-title d-flex align-items-center mb-3">
                <i class="bi bi-chat-left-text me-2 text-success"></i>
                <span>我的评论</span>
            </div>
            <ul class="list-group mb-4">
                <li class="list-group-item d-flex justify-content-between align-items-center" th:each="comment : ${myComments}">
                    <div class="d-flex flex-column w-100">
                        <div class="d-flex justify-content-between align-items-start">
                            <p class="mb-1 fw-medium text-truncate">
                                <i class="bi bi-chat-right-text me-2"></i>
                                <span th:text="${comment.content}"></span>
                            </p>
                            <small class="text-muted ms-3">
                                <i class="bi bi-clock me-1"></i>
                                <span th:text="${comment.createTime.format(T(java.time.format.DateTimeFormatter).ofPattern('yyyy-MM-dd HH:mm'))}"></span>
                            </small>
                        </div>
                        <div class="d-flex justify-content-between align-items-center mt-2">
<!--                            <span class="text-muted">-->
<!--                                <i class="bi bi-bookmark me-1"></i>-->
<!--                                文章：<a th:href="@{'/article/' + ${comment.articleId}}" th:text="${comment.articleTitle}"></a>-->
<!--                            </span>-->
                            <div>
                                <button class="btn btn-outline-primary btn-sm me-2" 
                                        type="button"
                                        onclick="editComment(/*[(${comment.commentId})]*/)">
                                    <i class="bi bi-pencil"></i> 编辑
                                </button>
                                <button class="btn btn-outline-danger btn-sm"
                                        type="button"
                                        onclick="confirmDelete('comment', /*[(${comment.commentId})]*/)">
                                    <i class="bi bi-trash3"></i> 删除
                                </button>
                            </div>
                        </div>
                    </div>
                </li>
                <li th:if="${#lists.isEmpty(myComments)}" class="list-group-item text-muted">
                    <i class="bi bi-chat-left-dots me-2"></i>暂无评论
                </li>
            </ul>
        </div>

<!-- 修改密码模态框 -->
<div class="modal fade" id="passwordModal" tabindex="-1" aria-labelledby="passwordModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="passwordModalLabel">修改密码</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="passwordForm">
          <div class="mb-3">
            <label for="currentPassword" class="form-label">当前密码</label>
            <input type="password" class="form-control" id="currentPassword" required>
          </div>
          <div class="mb-3">
            <label for="newPassword" class="form-label">新密码</label>
            <input type="password" class="form-control" id="newPassword" required>
          </div>
          <div class="mb-3">
            <label for="confirmPassword" class="form-label">确认新密码</label>
            <input type="password" class="form-control" id="confirmPassword" required>
          </div>
          <div id="passwordError" class="text-danger mb-3 d-none">错误提示</div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" onclick="changePassword()">保存更改</button>
      </div>
    </div>
  </div>
</div>

<!-- Toast 提示 -->
<div class="toast align-items-center text-bg-success border-0" role="alert" aria-live="assertive" aria-atomic="true" id="successToast" data-bs-delay="3000">
  <div class="d-flex">
    <div class="toast-body">
      头像更新成功！
    </div>
    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
</div>

<!-- 错误提示 -->
<div class="toast align-items-center text-bg-danger border-0" role="alert" aria-live="assertive" aria-atomic="true" id="errorToast" data-bs-delay="3000">
  <div class="d-flex">
    <div class="toast-body">
      头像上传过程中发生错误。
    </div>
    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
</div>

<!-- 密码修改成功提示 -->
<div class="toast align-items-center text-bg-success border-0" role="alert" aria-live="assertive" aria-atomic="true" id="passwordSuccessToast" data-bs-delay="3000">
  <div class="d-flex">
    <div class="toast-body">
      密码修改成功！
    </div>
    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
</div>

<!-- 密码验证错误提示 -->
<div class="toast align-items-center text-bg-danger border-0" role="alert" aria-live="assertive" aria-atomic="true" id="passwordErrorToast" data-bs-delay="3000">
  <div class="d-flex">
    <div class="toast-body">
      当前密码不正确！
    </div>
    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
</div>

<!-- 确认删除模态框 -->
<div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-labelledby="deleteConfirmLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title text-danger" id="deleteConfirmLabel">确认删除</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>确定要删除这个<span id="deleteItemType"></span>吗？此操作不可撤销。</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" onclick="performDelete()">删除</button>
            </div>
        </div>
    </div>
</div>

<!-- 文章查看模态框 -->
<div class="modal fade" id="articleViewModal" tabindex="-1" aria-labelledby="articleViewLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="articleViewLabel">文章预览</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <h3 id="articleTitle"></h3>
                <div class="text-muted mb-3">
                    <i class="bi bi-person me-1"></i><span id="articleAuthor"></span>
                    <span class="mx-2">|</span>
                    <i class="bi bi-clock me-1"></i><span id="articleDate"></span>
                </div>
                <div id="articleContent" class="article-content"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>



</body>
<script>
    // 存储当前删除目标
    let deleteTarget = { type: null, id: null };

    // 确认删除函数
    function confirmDelete(type, id) {
        deleteTarget = { type, id };
        document.getElementById('deleteItemType').textContent = type === 'article' ? '文章' : '评论';
        new bootstrap.Modal(document.getElementById('deleteConfirmModal')).show();
    }

    // 执行删除函数
    function performDelete() {
        if (deleteTarget.type && deleteTarget.id) {
            fetch(`localhost:8080/api/${deleteTarget.type}s/${deleteTarget.id}`, {
                method: 'DELETE',
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('Success:', data);
                    location.reload();
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        }
    }

    // 查看文章函数
    function viewArticle(id) {
        fetch(`localhost:8080/api/articles/${id}`)
            .then(response => response.json())
            .then(article => {
                document.getElementById('articleTitle').textContent = article.title;
                document.getElementById('articleAuthor').textContent = article.author;
                document.getElementById('articleDate').textContent = new Date(article.createTime).toLocaleDateString();
                document.getElementById('articleContent').innerHTML = `<p>${article.content}</p>`;

                new bootstrap.Modal(document.getElementById('articleViewModal')).show();
            })
            .catch(error => {
                console.error('Error:', error);
                alert('加载文章失败');
            });
    }

    // 撤回文章函数
    function retractArticle(id) {
        if (confirm('确定要撤回这篇文章吗？')) {
            fetch(`localhost:8080/api/articles/retract/${id}`, {
                method: 'POST',
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应异常');
                    }
                    return response.json();
                })
                .then(data => {
                    location.reload();
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('发生错误：' + error.message);
                });
        }
    }

    // 编辑文章函数
    function editArticle(id) {
        window.location.href = `/api/articles/newArticle?draftId=${id}`;
    }

    // 编辑评论函数
    function editComment(id) {
        window.location.href = `/user/comment/edit/${id}`;
    }

    // 修改密码函数
    function changePassword() {
        const currentPassword = document.getElementById('currentPassword').value;
        const newPassword = document.getElementById('newPassword').value;
        const confirmPassword = document.getElementById('confirmPassword').value;

        if (newPassword !== confirmPassword) {
            document.getElementById('passwordError').textContent = '新密码和确认密码不一致！';
            document.getElementById('passwordError').classList.remove('d-none');
            return;
        }

        fetch('localhost:8080/api/user/changePassword', {
            method: 'POST',
            body: JSON.stringify({ currentPassword, newPassword })
        })
            .then(response => {
                if (response.ok) {
                    document.getElementById('passwordSuccessToast').classList.add('show');
                    document.getElementById('passwordModal').querySelector('button[data-bs-dismiss="modal"]').click();
                } else {
                    document.getElementById('passwordErrorToast').classList.add('show');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('passwordErrorToast').classList.add('show');
            });
    }
</script>
</html>